package com.zd.miko.tally.MVP.Service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zd.miko.tally.Bean.ArticleBean;
import com.zd.miko.tally.Bean.ArticleSynBean;
import com.zd.miko.tally.Bean.RealmBean.RealmDiaryDetailBean;
import com.zd.miko.tally.EventBusBean.EventBusType;
import com.zd.miko.tally.MVP.ModuleEditor.EventBusMsg.MessageEvent;
import com.zd.miko.tally.R;
import com.zd.miko.tally.Utils.NetWorkUtils;
import com.zd.miko.tally.Utils.RetrofitParameterBuilder;
import com.zd.miko.tally.Utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import io.realm.Realm;
import io.realm.RealmResults;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class SynService extends IntentService {
    public SynService() {
        super("SynService");
    }

    public static Context c;
    private static final String TAG = "SynService";

    /**
     * Starts this service to perform action Foo with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    // TODO: Customize helper method
    public static void startService(Context context) {
        Intent intent = new Intent(context, SynService.class);
        context.startService(intent);
        c = context;
    }

    private int taskCounter = 0;

//    private void sendNotification() {
//        //获取NotificationManager实例
//        NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//        //实例化NotificationCompat.Builde并设置相关属性
//        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
//                //设置小图标
//                .setLargeIcon(BitmapFactory.decodeResource(getResources(),
//                        R.drawable.ic_cloud_circle_black_48dp))
//                .setSmallIcon(R.mipmap.ic_launcher)
//                //设置通知标题
//                .setContentTitle("Mei日记")
//                //设置通知内容
//                .setContentText("Wifi状态下自动同步日记");
//        //设置通知时间，默认为系统发出通知的时间，通常不用设置
//        //.setWhen(System.currentTimeMillis());
//        //通过builder.build()方法生成Notification对象,并发送通知,id=1
//        notifyManager.notify(1, builder.build());
//    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {

            Realm realm = Realm.getDefaultInstance();
            /**serach by id*/
            RealmResults<RealmDiaryDetailBean> realmBeans = realm
                    .where(RealmDiaryDetailBean.class).findAll();

            StringBuilder sb = new StringBuilder();
            for (RealmDiaryDetailBean diaryDetailBean : realmBeans) {
                sb.append(diaryDetailBean.getArticleId() + " ");
            }
            realm.close();

            RetrofitParameterBuilder builder = RetrofitParameterBuilder.newBuilder();

            builder.addParameter("articles", sb.toString());

            builder.addParameter("userId", Utils.getUserAccount());

            Utils.normalPost(builder, getString(R.string.syn), new Utils.PostCall() {
                @Override
                public void onSuccess(String response) {
                    if (response == null) {
                        Log.i(TAG, "response.body()" + " null");
                    } else {
                        ArticleSynBean articleSynBean = new Gson()
                                .fromJson(response, ArticleSynBean.class);

                        int synCount = articleSynBean.getPrepareDownloadArticleIds().size() +
                                articleSynBean.getPrepareUploadArticleIds().size();

                        /**如果为零则直接return*/
                        if (synCount == 0) {
                            Toast.makeText(SynService.this, "所有日记已同步",
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (NetWorkUtils.isWifiConnected(SynService.this)) {
                            Toast.makeText(SynService.this, synCount
                                            + "条记录同步中..",
                                    Toast.LENGTH_SHORT).show();

                            parseSysBean(articleSynBean);
                        } else {
                            AlertDialog confirmDialog = new AlertDialog
                                    .Builder(c).setTitle("确认")
                                    .setCancelable(false)
                                    .setMessage("发现" + synCount + "条日记未同步，" +
                                            "当前使用的是移动网络，同步会耗费较多流量是否马上同步？")
                                    .setPositiveButton("马上同步", (dialog, which) -> {
                                        dialog.dismiss();
                                        parseSysBean(articleSynBean);
                                        Toast.makeText(SynService.this, "同步中..",
                                                Toast.LENGTH_SHORT).show();
                                    })
                                    .setNegativeButton("取消", (dialog, which) -> {
                                        dialog.dismiss();
                                    })
                                    .create();

                            confirmDialog.show();

                        }

                    }
                }

                @Override
                public void onFail(String error) {

                }
            });

        }
    }

    public void parseSysBean(ArticleSynBean articleSynBean) {

        ArrayList<String> prepareDownloadArticles = (ArrayList<String>) articleSynBean
                .getPrepareDownloadArticleIds();
        ArrayList<String> prepareUploadArticles = (ArrayList<String>) articleSynBean
                .getPrepareUploadArticleIds();

        taskCounter = prepareDownloadArticles.size();

        for (String articleId : prepareDownloadArticles) {
            /**articleId对应的任务数初始化为0*/
            downloadArticleInfo(articleId);
        }

        /**上传*/
        for (String articleId : prepareUploadArticles) {
            UploadService.startService(this, articleId, null);
        }
    }


    private void downloadArticleInfo(String articleId) {
        RetrofitParameterBuilder builder = RetrofitParameterBuilder.newBuilder();

        builder.addParameter("articleId", articleId);

        Utils.normalPost(builder, getString(R.string.get_article_by_id), new Utils.PostCall() {
            @Override
            public void onSuccess(String response) {

                ArticleBean articleBean = new Gson().fromJson(response, ArticleBean.class);

                if (articleBean == null) {
                    return;
                }

                Realm realm = Realm.getDefaultInstance();
                realm.executeTransaction(realm1 -> {
                    RealmDiaryDetailBean diaryDetailBean = realm1
                            .createObject(RealmDiaryDetailBean.class);
                    diaryDetailBean.setLocationStr(articleBean.getLocation());
                    diaryDetailBean.setYear(articleBean.getYear());
                    diaryDetailBean.setEditTime(articleBean.getEditTime());
                    diaryDetailBean.setMonth(articleBean.getMonth());
                    diaryDetailBean.setDay(articleBean.getDay());
                    diaryDetailBean.setUserId(articleBean.getUserId());
                    diaryDetailBean.setContent(articleBean.getContent());
                    diaryDetailBean.setArticleId(articleBean.getArticleId());
                });

                taskCounter--;
                if (taskCounter == 0) {
                    // TODO: 2017/10/12
                    EventBus.getDefault().post(new MessageEvent("",
                            EventBusType.REFRESH_DIARY_LIST));
                }
            }

            @Override
            public void onFail(String error) {

            }
        });
    }
}
